<template>
  <div class="wrapper">
    <!-- 左侧包含查询控制面板 -->
    <div class="left-wrapper">
      <div class="query-controller">
        <div style="color: #fff; margin-bottom: 10px">查询模式选择</div>
        <div class="divide"></div>
        <div class="query-item" v-for="item in queryItems">
          <i
            :class="[
              'iconfont',
              item.icon,
              'commonIcon',
              item.active ? 'commonIconActive' : '',
            ]"
          ></i>
          <span
            :class="[
              'query-item-title',
              item.active ? 'query-item-title-active' : '',
            ]"
            @click="chooseQueryItem(item)"
          >
            {{ item.title }}
          </span>
        </div>
      </div>
    </div>
    <!-- 中间包含站点选择 -->
    <div class="center-wrapper" v-if="!isInRouteDesign">
      <!-- 地铁线路 -->
      <div id="subLine-controller">
        <div class="title-bg">
          <i class="iconfont metro-lineRoute"></i> 地铁线路
        </div>
        <div class="item-wrapper">
          <div
            class="item"
            v-for="item in subLineData"
            @click.stop="handleItemClick(item)"
          >
            <div
              class="box"
              :style="{
                borderColor: item.color,
                backgroundColor: item.choosed ? item.color : 'rgba(0,0,0,0)',
              }"
            ></div>
            <span :style="{ color: '#34c5cf' }">{{ item.name.slice(-3) }}</span>
          </div>
        </div>
      </div>
      <!-- 站点列表 -->
      <div id="station-controller">
        <div class="title-bg">
          <i class="iconfont metro-ditie"></i> 地铁站点
        </div>
        <div class="item-wrapper">
          <div
            class="item"
            v-for="item in stationData"
            @click="chooseStation(item)"
          >
            <div
              class="box"
              :style="{
                backgroundColor: item.choosed ? '#fff' : 'rgba(0,0,0,0)',
              }"
            ></div>
            <span :style="{ color: '#34c5cf' }">{{ item.name }}</span>
          </div>
        </div>
      </div>
    </div>
    <!-- 右边包含站控措施图例 -->
    <div class="right-wrapper">
      <!-- 站控措施,样式和查询控制选择保持一致 -->
      <div class="legend">
        <div class="title">
          <span style="margin-right: 14px">图标</span>
          <span>站控措施</span>
        </div>
        <div class="query-item" v-for="item in solutions">
          <i :class="['iconfont', item.iconName, 'commonIcon']"></i>
          <span class="query-item-title">
            {{ item.title }}
          </span>
        </div>
      </div>
    </div>
    <!-- 路径规划面板 -->
    <RouteDesign v-if="isInRouteDesign" />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { stationMangeItems, station_solutions } from '@/store/staticData'
import { renderHeat, focusOnStation, flyToEntireView } from '@/cesiumTools/effectController.js'
import RouteDesign from './RouteDesign.vue'
import { useLineData, useMeasureData } from '@/store'
const lineData = useLineData()
const measureDataStore = useMeasureData()
const solutions = ref(station_solutions)
let viewer // 地图实例
let removeHeat // 移除热力图
const queryItems = ref(stationMangeItems)
const subLineData = ref([]) // 地铁线路数据
const stationData = ref([]) // 站点列表数据
// 记录当前的地铁线路
const currentLine = ref('')
// 当前激活的查询模式
const queryWay = ref('')
// 当前是否在路径规划面板中
const isInRouteDesign = ref(false)

onMounted(() => {
  // console.log(lineData.allData)
  // 获取地铁线路数据
  subLineData.value = lineData.allData.map((item) => ({
    ...item,
    choosed: false,
  }))
  // viewer初始化
  viewer = lineData.viewer
  /* 切换隐藏侧边 */
  lineData.setSidebarShow(false)
})
/* 组件销毁时，移除热力图，恢复Panel */
onBeforeUnmount(() => {
  removeHeat && removeHeat()
  measureDataStore.clearData()
  lineData.setSidebarShow(true)
})

// 点击地铁线路，显示该线路的站点列表
const handleItemClick = (item) => {
  console.log(item)
  const { stationsList, id, name } = item
  currentLine.value = name
  stationData.value = stationsList
  subLineData.value = subLineData.value.map((n) => {
    n.choosed = id === n.id
    return n
  })
}

// 点击查询方式，改变查询的数据以及效果
const chooseQueryItem = (item) => {
  removeHeat && removeHeat()
  // 处理地图效果
  handleEffect(item.title)
  // 处理ui
  queryItems.value = queryItems.value.map((n) => {
    if (n.id === item.id) {
      n.active = true
      queryWay.value = item.title
    } else {
      n.active = false
    }
    return n
  })
}

// 根据查询方式处理效果
const handleEffect = (title) => {
  lineData.controlAll(true)
  isInRouteDesign.value = false
  measureDataStore.clearData()
  if (title === '站点拥挤度') {
    renderClowed()
  } else if (title === '路径规划') {
    isInRouteDesign.value = true
  } else if (title === '站控措施') {
    renderStationMeasure()
  }
}

// 渲染站控措施
const renderStationMeasure = () => {
  function getRandomIntInclusive(min, max) {
    min = Math.ceil(min)
    max = Math.floor(max)
    return Math.floor(Math.random() * (max - min + 1)) + min //含最大值，含最小值
  }

  // 从数组中随机取几个数
  const getRandomArrayValue = (arr, num) => {
    var sData = arr.slice(0),
      i = arr.length,
      min = i - num,
      item,
      index
    while (i-- > min) {
      index = Math.floor((i + 1) * Math.random())
      item = sData[index]
      sData[index] = sData[i]
      sData[i] = item
    }
    return sData.slice(min)
  }

  const resultData = []
  lineData.allData.forEach((item) => {
    const { stationsList, color } = item
    const result = stationsList.map((s) => {
      // 0-5个站控措施
      const measureNum = getRandomIntInclusive(0, 5)
      let measures = getRandomArrayValue(station_solutions, measureNum)
      s.measures = measures
      s.color = color
      return {
        name: s.name,
        measures,
      }
    })
    resultData.push(result)
  })
  // 全局共享站控措施数据
  measureDataStore.setData(resultData)
}

// 站点拥挤度逻辑,点击展示热力图，表现各个站点的拥挤程度
const renderClowed = () => {
  // 解析线路拥挤度数据
  const dataSource = []
  // 清除当前底图，然后添加arcgis底图
  subLineData.value.forEach((item) => {
    const { stationsList } = item
    stationsList.forEach((s) => {
      const { position } = s
      dataSource.push({
        x: position.lng,
        y: position.lat,
        value: Math.ceil(Math.random() * 1000),
      })
    })
  })
  removeHeat = renderHeat(viewer, dataSource)
  flyToEntireView(viewer)
}

// 点击站点，显示跳转到该站点
const chooseStation = (item) => {
  console.log(item)
  // 1.视角跳转到该处站点
  // 2.站点图标闪烁
  // 3.在linePrimitive中找到对应的实体
  // 4.根据对应的查询模式，做查询效果
  focusOnStation(viewer, item.name)

  stationData.value = stationData.value.map((v) => {
    if (v.name === item.name) {
      v.choosed = true
    } else {
      v.choosed = false
    }
    return v
  })
}
</script>

<style scoped>
.wrapper {
  width: 100%;
  height: 100%;
}

.left-wrapper {
  width: 23.438vw;
  height: 100%;
  position: absolute;
  left: 0;
  top: 2.083vw;
}

/* 查询方式选择样式 */
.query-controller {
  position: relative;
  width: 10.417vw;
  display: flex;
  flex-direction: column;
  margin-left: 1.771vw;
  margin-top: 1.042vw;
}

.query-item {
  margin: 4px;
  color: #fff;
  display: flex;
  align-items: center;
}

.commonIcon {
  padding: 2px 6px;
  font-size: 14px;
  background: url('/src/assets/uiResources/icon-wrapper.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  pointer-events: all;
  cursor: pointer;
  font-size: 15px;
  margin: 3px;
}

.commonIconActive {
  background: url('/src/assets/uiResources/icon-wrapper-active.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  color: #11916b;
}

.commonIcon:hover {
  background: url('/src/assets/uiResources/icon-wrapper-active.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.query-item-title {
  display: inline-block;
  padding: 3px 10px;
  font-size: 10px;
  margin-left: 20px;
  background: url('/src/assets/uiResources/button.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  position: relative;
  cursor: pointer;
  pointer-events: all;
  font-size: 15px;
  margin: 3px;
}

.query-item-title-active {
  background: url('/src/assets/uiResources/button-active.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
  color: #11916b;
}

.query-item-title:hover {
  background: url('/src/assets/uiResources/button-active.png');
  background-size: 100% 100%;
  background-repeat: no-repeat;
}

.query-item-title::after {
  content: '';
  width: 10px;
  height: 1px;
  background-color: rgba(224, 193, 193, 0.693);
  position: absolute;
  top: 50%;
  left: -10px;
}

.divide {
  width: 1px;
  height: 86%;
  position: absolute;
  top: 30px;
  left: 40px;
  background-color: rgba(224, 193, 193, 0.693);
}

/* 地铁线路列表 */
#subLine-controller {
  position: absolute;
  bottom: 0px;
  left: 34%;
  transform: translateX(-50%);
  width: 7.625vw;
  height: 8.292vw;
  background-color: rgba(0, 0, 0, 0.3);
  border: 1px solid #ab7818;
  display: flex;
  flex-direction: column;
}

.box {
  width: 10px;
  height: 10px;
  border-width: 1px;
  border-style: solid;
  background: transparent;
  user-select: all;
  cursor: pointer;
  transition: all 0.3s linear;
}

.item {
  width: 3.385vw;
  height: 1.042vw;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 0 0.156vw;
  background-color: rgba(255, 255, 255, 0.2);
  border: 1px solid #885f12;
  color: #fff;
  font-size: 0.521vw;
  pointer-events: all;
  cursor: pointer;
}

.item:hover {
  border: 1px solid #d8961a;
}

.item > span {
  line-height: 0.469vw;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  max-width: 2.083vw;
}

.item > input {
  outline: none;
  border: none;
  transition: all 0.3s ease;
}

.item-wrapper {
  display: flex;
  justify-content: space-around;
  align-content: space-around;
  flex-wrap: wrap;
  flex: 1;
  padding: 4px;
  overflow: hidden;
}

/* 站点列表 */
#station-controller {
  width: 33.458vw;
  height: 8.292vw;
  border: 1px solid #ab7818;
  background-color: rgba(0, 0, 0, 0.3);
  position: absolute;
  left: 39%;
  bottom: 0px;
  color: #fff;
  display: flex;
  flex-direction: column;
}

#station-controller .item-wrapper {
  justify-content: flex-start;
}

#station-controller .item {
  margin: 0 7px;
}

.title-bg {
  width: 100%;
  height: 30px;
  background: url('/src/assets/uiResources/title-bg.png');
  background-size: contain;
  color: #fff;
  background-repeat: no-repeat;
  line-height: 30px;
  margin-left: 10px;
  background: rgb(255, 255, 255);
  background-image: linear-gradient(
    180deg,
    rgba(255, 255, 255, 1) 9%,
    rgba(211, 156, 50, 1) 57%
  );
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
}

/* 站控措施图例 */
.right-wrapper {
  width: 13.417vw;
  height: 100%;
  position: absolute;
  right: 0px;
  top: 4.083vw;
}

.right-wrapper .query-item-title {
  cursor: default;
  pointer-events: none;
  font-size: 15px;
  margin: 3px;
}

.right-wrapper .query-item-title::after {
  width: 20px;
  left: -20px;
}

.legend .query-item i {
  pointer-events: none;
  cursor: default;
  font-size: 20px;
  margin: 3px;
}

.title {
  color: #fff;
}
</style>

